// ignore_for_file: use_build_context_synchronously

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_house_manager/api/home.dart';
import 'package:flutter_house_manager/pages/Home/components/home_list.dart';
import 'package:flutter_house_manager/pages/Home/components/home_nav.dart';
import 'package:flutter_house_manager/utils/TokenManager.dart';
import 'package:flutter_house_manager/utils/toast.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List _announceList = [];

  @override
  void initState() {
    super.initState();
    getAnnounceList();
  }

  /// 1. 获取公共列表
  getAnnounceList() async {
    try {
      final data = await getAnnounceListAPI();
      PromptAction.showSuccess('获取公共列表成功');
      setState(() {
        _announceList = data;
      });
    } catch (e) {
      PromptAction.showError('获取公共列表失败');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('享+社区'),
        ),
        body: ListView(
          children: [
            // testToken(),
            // testTimer(),
            const HomeNav(),
            Container(
                margin: const EdgeInsets.all(10),
                child: Image.asset('assets/images/banner@2x.jpg')),
            HomeList(list: _announceList)
          ],
        ));
  }

  int _count = 60;
  Timer? _timer;

  testTimer() {
    return Row(
      children: [
        ElevatedButton(
          onPressed: () {
            if (_timer != null) {
              return;
            }
            _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
              setState(() {
                _count--;
              });
            });
          },
          child: const Text('开始'),
        ),
        Text('$_count s'),
        ElevatedButton(
          onPressed: () {
            _timer?.cancel();
            _timer = null;
          },
          child: const Text('结束'),
        )
      ],
    );
  }

  testToken() {
    return Row(
      children: [
        ElevatedButton(
            onPressed: () {
              tokenManager.setToken('123456');
            },
            child: const Text('设置token')),
        ElevatedButton(
            onPressed: () async {
              final token = tokenManager.getToken();
              PromptAction.showSuccess('token: $token');
            },
            child: const Text('获取token')),
        ElevatedButton(
            onPressed: () async {
              await tokenManager.removeToken();
              PromptAction.showSuccess('删除token成功');
            },
            child: const Text('删除token'))
      ],
    );
  }
}
